<template>
  <view class="w-full">
    <view class="flex-center justify-between p-3">
      <text class="text-[32rpx] font-bold block">个人健康标签</text>
      <IconFont name="close" size="16" color="#999" @click="onClose" />
    </view>


    <ThreeLevelDirectory ref="directoryRef" :show-add-button="true" :add-button-text="addButtonText" @change="onDirectoryChange" @add="onAddItem">
      <!-- 内容插槽 -->
      <template #content="{ currentItem, level1, level2 }">
        <view v-if="loading" class="loading-state">
          <view class="loading-spinner"></view>
          <text class="loading-text">正在加载标签...</text>
        </view>

        <view v-if="currentItem">
            <view v-if="tagsList.length > 0" class="two-column-layout">
              <view class="item-card" v-for="item in tagsList" :key="item.id" @click="onNurseClick(item)">
             
                <text class="chip-text">{{ item.name || "未知" }}</text>
                <view class="chip-dot"></view>
              </view>
            </view>

          <!-- 空状态提示 -->
          <view v-else class="empty-state">
            <nut-empty description="暂无相关标签"></nut-empty>
          </view>

          <!-- 自定义标签添加区域 -->
          <view class="custom-tag-section">
            <view class="custom-tag-header">
              <view class="custom-tag-icon">✨</view>
              <view class="custom-tag-content">
                <text class="custom-tag-title">找不到合适的标签？</text>
                <text class="custom-tag-desc">您可以创建专属的个人健康标签</text>
              </view>
            </view>
            <nut-button type="primary" size="small" class="custom-tag-btn" @click="onAddTag">
              <text class="btn-text">+ 添加自定义标签</text>
            </nut-button>
          </view>
        </view>
      </template>
    </ThreeLevelDirectory>

    <!-- 添加标签弹窗 -->
    <AddTagPopup v-model="showAddPopup" :title="`添加${addLevelText}`" :placeholder="`请输入${addLevelText}名称`" @confirm="onConfirmAddTag" @cancel="closeAddPopup" />

    <AddTagPopup v-model="showAddTagPopup" :title="`添加自定义标签`" :placeholder="`请输入自定义标签名称`" @confirm="onConfirmAddTagCustom" @cancel="showAddTagPopup = false" />
  </view>
</template>

<script setup>
import { ref, watch } from "vue";
import ThreeLevelDirectory from "@/components/ThreeLevelDirectory.vue";
import AddTagPopup from "@/components/AddTagPopup.vue";
import { request } from "@/service/request";
import Taro from "@tarojs/taro";
import defaultAvatar from "@/assets/imgs/none.png";
import { IconFont } from '@nutui/icons-vue-taro'

const showAddTagPopup = ref(false);
const emit = defineEmits(['close']);
const onClose = () => {
  emit('close');
};
// 添加按钮文本配置
const addButtonText = ref({
  level1: "添加部门",
  level2: "添加科室",
  level3: "添加项目",
});

const tagsList = ref([]);

// 护士列表数据
const nurseList = ref([]);
const loading = ref(false);
const currentSelectedItem = ref(null);

// 监听选中项变化，请求标签列表
watch(currentSelectedItem, (newVal) => {
  if (newVal && newVal.id) {
    getTagList();
  } else {
    nurseList.value = [];
  }
});

// 三级目录组件ref
const directoryRef = ref(null);

// 添加标签弹窗相关
const showAddPopup = ref(false);
const addLevelText = ref("");
const addParentId = ref(null);

// 获取护士列表
const getNurseList = async (tagId) => {
  try {
    loading.value = true;
    console.log("获取护士列表, tagId:", tagId);

    const params = {
      pageSize: 12,
      pageNo: 1,
      isHealth: 1,
    };

    // 如果有tagId，添加到参数中
    if (tagId) {
      params.projectid = tagId;
    }

    const res = await request.get("/health_records/health_tag_info/healthTagInfo/rootList", params, {
      useErrMsg: true,
    });

    console.log("护士列表数据:", res);

    if (res.success && res.success.records) {
      nurseList.value = res.success.records;
    } else if (res.success && Array.isArray(res.success)) {
      nurseList.value = res.success;
    } else {
      nurseList.value = [];
    }
  } catch (error) {
    console.error("获取护士列表失败:", error);
    nurseList.value = [];
  } finally {
    loading.value = false;
  }
};

// 目录变化事件
const onDirectoryChange = ({ level, item }) => {
  console.log(`目录变化 - 级别${level}:`, item);
  currentSelectedItem.value = item;

  // 第三级目录变化时，获取护士列表
  if (level === 3 && item && !item.isAddButton) {
    getNurseList(item.id);
  }
};

// 添加项目事件
const onAddItem = ({ level, parentId }) => {
  console.log(`添加项目 - 级别${level}, 父级ID:`, parentId);

  const levelText = level === 1 ? "部门" : level === 2 ? "科室" : "项目";

  // 设置弹窗数据
  addLevelText.value = levelText;
  addParentId.value = parentId;

  // 显示弹窗
  showAddPopup.value = true;
};

// 关闭添加弹窗
const closeAddPopup = () => {
  showAddPopup.value = false;
};

// 确认添加
const onConfirmAddTag = async (name) => {
  if (!name || !name.trim()) {
    Taro.showToast({
      title: "名称不能为空",
      icon: "none",
    });
    return;
  }

  // 调用接口添加
  await addTag(name.trim(), addParentId.value, addLevelText.value);
};

// 添加自定义标签确认
const onConfirmAddTagCustom = async (name) => {
  console.log("添加自定义标签确认", name);
  showAddTagPopup.value = false;
  const params = {
    name,
    projectid: currentSelectedItem.value.id,
  };
  const res = await request.post("/health_records/health_tag_info/healthTagInfo/add", params, {
    useErrMsg: true,
  });
  if (res.error) {
    Taro.showToast({
      title: res.error.message,
      icon: "none",
    });
    return;
  } else {
    Taro.showToast({
      title: "添加成功",
      icon: "success",
    });
    getTagList();
  }
  console.log("添加自定义标签结果", res);
};

const getTagList = async () => {
  tagsList.value = [];
  if(!currentSelectedItem.value.id) {
    return;
  }
  const res = await request.get(
    "/health_records/health_tag_info/healthTagInfo/rootList",
    {
      projectid: currentSelectedItem.value.id,
    },
    {
      useErrMsg: true,
    }
  );

  console.log("获取标签列表结果", res);
  if (res.success.records) {
    tagsList.value = res.success.records;
  }
};

// 添加自定义标签
const onAddTag = () => {
  console.log("添加自定义标签", currentSelectedItem.value);
  showAddTagPopup.value = true;
};

// 添加标签
const addTag = async (name, pid, levelText) => {
  try {
    Taro.showLoading({
      title: "添加中...",
    });

    const params = {
      name,
      projectid: pid || null,
    };

    console.log("添加标签参数:", params);

    const res = await request.post("/health_records/health_tag_info/healthTagInfo/add", params, {
      useErrMsg: true,
    });

    console.log("添加标签结果:", res);

    if (res.success) {
      Taro.hideLoading();
      Taro.showToast({
        title: `${levelText}添加成功`,
        icon: "success",
      });

      // 刷新三级目录数据
      setTimeout(() => {
        if (directoryRef.value && directoryRef.value.refresh) {
          directoryRef.value.refresh();
        }
      }, 1500);
    } else {
      Taro.hideLoading();
      Taro.showToast({
        title: res.message || "添加失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("添加标签失败:", error);
    Taro.hideLoading();
    Taro.showToast({
      title: "添加失败",
      icon: "none",
    });
  }
};

// 护士点击事件
const onNurseClick = (nurse) => {
  console.log("点击护士:", nurse);

  // 跳转到护士详情页
  // Taro.navigateTo({
  //   url: `/pages/nurse/detail?id=${nurse.id}`,
  // });
};
</script>

<style lang="scss" scoped>
// 标签网格布局
.two-column-layout {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  padding: 16rpx 0;

  .item-card {
    flex: 0 0 calc(33.33% - 14rpx);
    padding: 12rpx 8rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    background: transparent;
    border-radius: 0;
    box-shadow: none;
    transition: transform 0.2s ease;
    position: relative;
    border: 2rpx solid #56a5f0;
   
    &:active {
      transform: translateY(4rpx);
      background: #f0f0f0;
    }


    .chip-text {
      font-size: 26rpx;
      font-weight: 600;
      letter-spacing: 0.5rpx;
      color: #2b85d9;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .chip-dot {
      width: 16rpx;
      height: 16rpx;
      background: url('../../../../src/assets/imgs/core.png') no-repeat center center;
      background-size: 100% 100%;
      position: absolute;
      top: 0;
      right: 0;
    }
  }
}

// 自定义标签添加区域
.custom-tag-section {
  margin-top: 40rpx;
  padding: 32rpx;
  background: linear-gradient(135deg, #FFF7F0 0%, #FFEEDB 100%);
  border-radius: 20rpx;
  border: 2rpx solid #FFE3C2;

  .custom-tag-header {
    display: flex;
    align-items: flex-start;
    margin-bottom: 24rpx;

    .custom-tag-icon {
      font-size: 32rpx;
      margin-right: 16rpx;
      margin-top: 4rpx;
    }

    .custom-tag-content {
      flex: 1;

      .custom-tag-title {
        display: block;
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }

      .custom-tag-desc {
        display: block;
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
      }
    }
  }

  .custom-tag-btn {
    width: 100%;
    height: 72rpx;
    border-radius: 16rpx;
    background: linear-gradient(135deg, #FF8A00 0%, #FF5A00 100%);
    border: none;
    box-shadow: 0 6rpx 16rpx rgba(255, 138, 0, 0.3);
    transition: all 0.3s ease;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 4rpx 12rpx rgba(255, 138, 0, 0.4);
    }

    .btn-text {
      font-size: 28rpx;
      font-weight: 600;
      color: #fff;
    }
  }
}

// 加载状态样式（橙色主题）
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;

  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #FF8A00;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 24rpx;
  }

  .loading-text {
    font-size: 28rpx;
    color: #666;
    font-weight: 500;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

// 页面标题优化（橙色主题）
.text-lg {
  background: linear-gradient(135deg, #FF8A00 0%, #FF5A00 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-weight: 700;
  letter-spacing: 1rpx;
}
</style>
